var Snail = window.Snail || {};
Snail.success = function (msg) {
    Snail.getMessageDiv('success').text(msg).show();
    Snail.messageFadeOut();
};
Snail.error = function (msg) {
    Snail.getMessageDiv('danger').text(msg).show();
    Snail.messageFadeOut();
};
Snail.messageFadeOut = function () {
    setTimeout(function () {
        $('.message').slideUp(200);
    }, 2000);
};
Snail.getMessageDiv = function (c) {
    return $('.message.alert-' + c).length > 0 ?
        $('.message.alert-' + c)
        :
        $('<div>').addClass('message alert alert-' + c).prependTo('body');
};
Snail.mask = function() {
    $('<div id="mask">').appendTo('body');
};
Snail.removeMask = function() {
    $('#mask').remove();
};
Snail.getCsrfToken = function(){
    return Snail._csrfToken;
};

$(function () {

    if (Snail._message) {
        $('<div>')
            .addClass('message alert alert-' + Snail._message[1])
            .text(Snail._message[0])
            .prependTo('body');
        Snail.messageFadeOut();
    }

    $('form.cmd-async').submit(function () {
        var $form = $(this);
        Snail.mask();
        $.ajax({
            url: $form.attr('action'),
            dataType: "json",
            method: $form.attr('method') || 'get',
            data: $form.serialize()
        })
            .success(function(resp){
                if (resp.message) {
                    if (!resp.code) { // 成功
                        Snail.success(resp.message);
                    } else {
                        Snail.error(resp.message);
                    }
                    if (resp.redirect) {
                        setTimeout(function(){
                            window.location.href = resp.redirect;
                        }, resp.redirect_day || 1000);
                    }
                } else {
                    if (resp.redirect) {
                        window.location.href = resp.redirect;
                    }
                }
            })
            .always(function(){
                Snail.removeMask();
            });
        return false;
    });

    $('body')
        .on('click', '.message', function () {
            $(this).hide();
        })
        .on('click', 'a.cmd-post,a[data-confirm]', function(){
            var $href = $(this);
            var tip = $(this).data('confirm');
            if ((tip && confirm(tip)) || !tip) {
                if ($href.is('.cmd-post')) {
                    var $form = $('<form method="post">')
                        .attr('action', $href.attr('href'))
                        .append('<input type="hidden" name="_csrf" value="' + Snail.getCsrfToken() + '">')
                        .appendTo('body');
                    $form.submit();
                } else {
                    window.location.href = $href.attr('href');
                }
            }
            return false;
        })

});

$(function () {
    $('[data-toggle="tooltip"]').tooltip()
})